×
☰ See All Chapters

Selenium relative xpath using contains function - XPath contains(text)

In the html code of an element, if the attribute value or the text is changing partially, then use contains() function to identify the element.  In order to use contains() function, the element should have either attribute value or text value. We use contains() function when the text value is very lengthy or the attribute value is very lengthy.

Syntax:

//tagname[contains(@attributeName,'attributeValue')]

//tagname[contains(text(),'text value of the tag')]

Few examples for relative xpath using contains() function for the below sample html code

<html>

</head>

<body>

<table align="center" width=90% cellspacing="2" cellpadding="2" >

        <tr>

                <td>Row 1 : </td>

                <td><input type="text" id="xyz"></td>

        </tr>

        <tr>

                <td>Row 2 : </td>

                <td><input type="text" name="lmn"></td>

        </tr>

        <tr>

                <td>Row 3 : </td>

                <td><button type="button">www.tools4testing.com</button></td>  

        </tr>

        <tr>

                <td>Row 4 : </td>  

                <td><button type="button">www.java4coding.com</button></td>  

        </tr>

</table>

</body>

</html>

 

Relative XPath expressions using contains ()

 Matching Element

xpath=//input[contains(@id,'xyz')]

Row 1 Input

xpath=//input[contains(@name,'lmn')]

Row 2 Input

xpath=//button[contains(text(),'www.tools4testing.com')]

Row 3 Button

xpath=//button[contains(text(),'www.java4coding.com')]

Row 4 Button

You can write the script and test these using our Test Page

selenium-relative-xpath-using-contains-function-0
 
selenium-relative-xpath-using-contains-function-1
 

All Chapters
Author